<template>
  <view class="container">
    <!-- #ifdef MP-WEIXIN -->
    <uv-navbar :fixed="false" :title="title" leftIcon="" />
    <!-- #endif -->
    <view class="bg-white">
      <uv-tabs
        :list="tabListType"
        :current="current1"
        @change="change2"
        keyName="name"
        lineColor="#e45656"
      ></uv-tabs>
      <uv-tabs
        :list="tabList"
        :current="current"
        @change="change"
        keyName="name"
        :scrollable="false"
        v-if="orderType != 'due'"
      ></uv-tabs>
      <uv-tabs
        :list="dueTabList"
        :current="current2"
        @change="change"
        keyName="name"
        :scrollable="false"
        v-if="orderType == 'due'"
      ></uv-tabs>
    </view>
    <view
      class="orders-list d-flex flex-column w-100"
      style="padding: 20rpx; padding-bottom: 80rpx"
    >
      <view
        class="order-item"
        v-for="(item, index) in orders"
        :key="index"
        style="margin-bottom: 30rpx"
      >
        <list-cell :hover="false">
          <view class="w-100 d-flex align-items-center">
            <view class="flex-fill d-flex flex-column">
              <view
                class="font-size-lg text-color-base"
                style="margin-bottom: 20rpx"
              >
                {{ item.shop?.name || item.shop_name }}
              </view>
              <view class="flex align-center">
                <view class="mr-1">
                  <uv-tags
                    :text="currentLanguageTexts.due"
                    plain
                    size="mini"
                    type="error"
                    v-if="orderType == 'due'"
                  ></uv-tags>
                  <uv-tags
                    :text="currentLanguageTexts.desk"
                    plain
                    size="mini"
                    type="error"
                    v-if="item.orderType == 'desk'"
                  ></uv-tags>
                  <uv-tags
                    :text="currentLanguageTexts.takein"
                    plain
                    size="mini"
                    type="error"
                    v-if="item.orderType == 'takein'"
                  ></uv-tags>
                  <uv-tags
                    :text="currentLanguageTexts.takeout"
                    plain
                    size="mini"
                    type="error"
                    v-if="item.orderType == 'takeout'"
                  ></uv-tags>
                </view>
                <view class="font-size-sm text-color-assist"
                  >{{ currentLanguageTexts.orderNo }}：{{
                    item.orderId || item.orderNumber
                  }}</view
                >
                <!-- <view class="font-size-base text-color-assist" v-if="item.orderType == 'desk'">桌号:{{ item.deskNumber }}</view>
								<view class="font-size-base text-color-assist" v-else>取餐号:{{ item.numberId }}</view> -->
              </view>
            </view>
            <view class="font-size-medium text-color-primary">
              {{
                item.statusDto?.title
                  ? currentLanguageTexts[`${item.statusDto.title}`] ||
                    item.statusDto.title
                  : dueTabList.find((el) => el.type == item.status).name
              }}
            </view>
          </view>
        </list-cell>
        <list-cell :hover="false" last>
          <view class="w-100 d-flex flex-column">
            <!-- <block v-if="orderType == 'due'">
              <view
                class="w-100 text-truncate font-size-lg text-color-base"
                style="margin-bottom: 20rpx"
              >
                <view class="flex mb-2">
                  <image
                    :src="item.appShopDeskVO.image"
                    mode="aspectFill"
                    class="image"
                  ></image>
                  <view class="flex flex-column">
                    <view class="font-size-medium mt-1 text-color-base">{{
                      item.appShopDeskVO.title
                    }}</view>
                    <view class="font-size-sm mt-1"
                      >桌号:{{ item.appShopDeskVO.number }}</view
                    >
                    <view class="font-size-sm mt-1">×1 $0.00</view>
                  </view>
                </view>
              </view>
            </block> -->
            <block v-if="orderType !== 'due'">
              <view
                class="w-100 text-truncate font-size-lg text-color-base"
                style="margin-bottom: 20rpx"
                v-if="item.cartInfo.length <= 3"
              >
                <view
                  class="flex mb-2"
                  v-for="(good, index) in item.cartInfo"
                  :key="index"
                >
                  <image
                    :src="good.image"
                    mode="aspectFill"
                    class="image"
                  ></image>
                  <view class="flex flex-column">
                    <view class="font-size-medium mt-1 text-color-base">{{
                      good.title
                    }}</view>
                    <view class="font-size-sm mt-1">{{ good.spec }}</view>
                    <view class="font-size-sm mt-1"
                      >×{{ good.number }} ${{ good.price }}</view
                    >
                  </view>
                </view>
              </view>
              <view
                class="w-100 text-truncate font-size-lg text-color-base flex flex-wrap"
                style="margin-bottom: 20rpx"
                v-else
              >
                <view
                  class="flex mb-2 justify-center"
                  style="margin-right: 3rpx"
                  v-for="(good, index) in item.cartInfo"
                  :key="index"
                >
                  <image
                    :src="good.image"
                    mode="aspectFill"
                    class="image"
                  ></image>
                </view>
              </view>
            </block>
            <view
              class="d-flex justify-content-between align-items-center"
              style="margin-bottom: 30rpx"
              v-if="orderType !== 'due'"
            >
              <view class="font-size-sm text-color-assist">
                {{ formatDateTime(item.createTime) }}
              </view>
              <view
                class="d-flex font-size-sm text-color-base align-items-center"
              >
                <view style="margin-right: 10rpx"
                  >{{
                    currentLanguageTexts.totalItems(goodsNum(item.cartInfo))
                  }}，{{ currentLanguageTexts.actualPay }}</view
                >
                <view class="font-size-lg">${{ item.payPrice }}</view>
              </view>
            </view>
            <view v-else>
              <view
                >{{ currentLanguageTexts.waitNumberText }}：{{
                  item.queue_users
                }}人</view
              >
              <view class="mt-1"
                >{{ currentLanguageTexts.waitTimeText }}：{{
                  item.wait_time
                }}
                min</view
              >
              <view class="mt-1"
                >{{ currentLanguageTexts.mealTiemText }}：{{ item.meal_time }}
              </view>
              <view class="mt-1" v-if="item.desk_code">
                {{ currentLanguageTexts.tableNumber }}：{{ item.desk_code }}
              </view>
            </view>
            <view class="d-flex align-items-center justify-content-end">
              <uv-button
                v-if="orderType == 'due' && item.status == 0"
                class="left-margin"
                plain
                type="error"
                shape="circle"
                :hairline="false"
                @click="cancelDueOrder(item.order_id)"
              >
                {{ currentLanguageTexts.cancelDue }}
              </uv-button>
              <uv-button
                v-if="
                  item.paid > 0 && item.status < 2 && item.refundStatus == 0
                "
                class="left-margin"
                type="primary"
                shape="circle"
                plain
                @tap="receive(item)"
              >
                {{ currentLanguageTexts.confirmReceipt }}
              </uv-button>
              <uv-button
                class="left-margin"
                plain
                :hairline="false"
                shape="circle"
                v-if="orderType !== 'due'"
                @tap="detail(item.orderId)"
              >
                {{ currentLanguageTexts.orderDetail }}
              </uv-button>
            </view>
          </view>
        </list-cell>
      </view>
    </view>
    <uv-empty
      v-if="orders.length == 0"
      :text="currentLanguageTexts.noData"
    ></uv-empty>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useMainStore } from '@/store/store';
import { storeToRefs } from 'pinia';
import {
  onShow,
  onLoad,
  onPullDownRefresh,
  onReachBottom,
} from '@dcloudio/uni-app';
import { formatDateTime, kmUnit } from '@/utils/util';
import { orderGetOrders, orderReceive } from '@/api/order';
import { DoGetBookInfo, DoCancelBook } from '@/api/due';
const main = useMainStore();
const { isLogin, tgUser, currentLanguageTexts, member } = storeToRefs(main);
const title = ref('我的订单');

const page = ref(1);
const pageSize = ref(10);
const orders = ref([]);
const tabListType = computed(() => [
  {
    type: 'takein',
    name: currentLanguageTexts.value.takein,
  },
  {
    type: 'takeout',
    name: currentLanguageTexts.value.takeout,
  },
  {
    type: 'desk',
    name: currentLanguageTexts.value.desk,
  },
  {
    type: 'due',
    name: currentLanguageTexts.value.due,
  },
]);
const tabList = computed(() => currentLanguageTexts.value.orderStatusList);
const dueTabList = computed(() => currentLanguageTexts.value.dueStatusList);
// const orderStatusList =
const current = ref(0);
const current1 = ref(0);
const current2 = ref(0);
const type = ref(-1);
const orderType = ref('takein');

const orderGoodsName = computed(() => {
  //计算单个饮品添加到购物车的数量
  return (goods) => {
    let arr = [];
    goods.forEach((good) => arr.push(good.title + '*' + good.number));
    return arr.join('，');
  };
});
const goodsNum = computed(() => {
  //计算单个饮品添加到购物车的数量
  return (goods) => {
    let num = 0;
    goods.forEach((good) => (num += parseInt(good.number)));
    return num;
  };
});

onLoad((option) => {
  if (option.current) {
    current.value = option.current;
    type.value = tabList.value[option.current].type;
  }
  uni.setTabBarItem({
    index: 0,
    text: currentLanguageTexts.value.homePage,
  });
  uni.setTabBarItem({
    index: 1,
    text: currentLanguageTexts.value.orderingMeal,
  });
  uni.setTabBarItem({
    index: 2,
    text: currentLanguageTexts.value.menuOrder,
  });
  uni.setTabBarItem({
    index: 3,
    text: currentLanguageTexts.value.mine,
  });
});
onShow(() => {
  if (!isLogin.value) {
    return uni.navigateTo({ url: '/pages/components/pages/login/login' });
  }
  getOrders(false);
});
onPullDownRefresh(() => {
  getOrders(false);
});
onReachBottom(() => {
  getOrders(false);
});

// tab栏切换
const change = (e) => {
  type.value = e.type;
  getOrders(true);
};

const change2 = (e) => {
  orderType.value = e.type;
  type.value = -1;
  getOrders(true);
};

const getOrders = async (isRefresh = false) => {
  uni.showLoading({
    title: currentLanguageTexts.value.loading,
  });
  if (isRefresh) {
    orders.value = [];
    page.value = 1;
  }
  if (orderType.value == 'due') {
    if (isRefresh) {
      console.log(member.value);
      DoGetBookInfo({
        id: member.value.id,
        chatId: tgUser.value.chat_id,
        status: type.value,
      }).then((res) => {
        orders.value = res?.list || [];
      });
    }
  } else {
    let ordersData = await orderGetOrders({
      page: page.value,
      limit: pageSize.value,
      type: type.value,
      orderType: orderType.value,
    });

    if (ordersData) {
      orders.value = orders.value.concat(ordersData);
      page.value += 1;
    }
  }

  uni.stopPullDownRefresh();
  uni.hideLoading();
};
const detail = (id) => {
  uni.navigateTo({
    url: '/pages/components/pages/orders/detail?id=' + id,
  });
};
// 确认收到货
const receive = async (order) => {
  let data = await orderReceive({ uni: order.orderId });
  if (data) {
    await getOrders(true);
  }
};

const cancelDueOrder = async (orderNumber) => {
  await DoCancelBook({
    id: orderNumber,
    chatId: tgUser.value.chat_id,
  });
  uni.showToast({
    title: currentLanguageTexts.value.operateSuccessfully,
    icon: 'none',
  });
  await getOrders(true);
};
</script>

<style lang="scss" scoped>
.left-margin {
  margin-left: 10rpx;
}
.image {
  width: 130rpx;
  height: 130rpx;
  margin-right: 30rpx;
  border-radius: 8rpx;
}
</style>
